package com.ruoyi.web.controller.module.order;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.customer.domain.CustomerUser;
import com.ruoyi.customer.service.ICustomerUserService;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.service.IEmployeeUserService;
import com.ruoyi.market.domain.*;
import com.ruoyi.market.service.*;
import com.ruoyi.order.domain.OrderGoods;
import com.ruoyi.order.service.IOrderGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 商品订单信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/order/goods")
public class OrderGoodsController extends BaseController
{
    @Autowired
    private IOrderGoodsService orderGoodsService;

    @Autowired
    private ICustomerUserService customerUserService;

    @Autowired
    private IEmployeeUserService employeeUserService;

    @Autowired
    private ILevelService levelService;

    @Autowired
    private IConfigOrderService configOrderService;

    @Autowired
    private IConfigEmployeeService configEmployeeService;

    @Autowired
    private IConfigPayService configPayService;

    @Autowired
    private IConfigProgramService configProgramService;

    /**
     * 获取商品订单列表
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/orderGoodsList")
    public TableDataInfo list(@RequestBody OrderGoods orderGoods, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            orderGoods.setShopId(shopId);
        }
        startPageByPost();
        List<OrderGoods> list = orderGoodsService.selectOrderGoodsList(orderGoods);
        return getDataTable(list);
    }

    @Log(title = "商品订单管理 - 导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('order:goods:export')")
    @PostMapping("/orderGoodsExport")
    public void export(HttpServletResponse response, OrderGoods orderGoods)
    {
        List<OrderGoods> list = orderGoodsService.selectOrderGoodsList(orderGoods);
        ExcelUtil<OrderGoods> util = new ExcelUtil<OrderGoods>(OrderGoods.class);
        util.exportExcel(response, list, "商品订单数据");
    }

    /**
     * 根据商品订单编号获取详细信息
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @GetMapping(value = { "/", "/{orderNo}" })
    public AjaxResult getInfo(@PathVariable(value = "orderNo", required = false) String orderNo)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(orderNo))
        {
            OrderGoods orderGoods = orderGoodsService.selectOrderGoodsByOrderNo(orderNo);
            ajax.put(AjaxResult.DATA_TAG, orderGoods);
        }
        return ajax;
    }

    /**
     * 新增商品订单 - 客户下单
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @Log(title = "商品订单管理 - 新增商品订单", businessType = BusinessType.INSERT)
    @PostMapping("/orderGoodsCreate")
    public AjaxResult orderGoodsCreate(@Validated @RequestBody OrderGoods orderGoods, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            orderGoods.setShopId(shopId);
        }
        if(orderGoods.getActualAmount().compareTo(new BigDecimal(0)) <= 0){
            return AjaxResult.error("操作失败：实付金额不能低于0");
        }
        Long userId = SecurityUtils.getUserId();
        CustomerUser cu = customerUserService.selectUserById(userId);
        customerUserService.checkUserAllowed(cu);
        AjaxResult ajax = AjaxResult.success();

        ConfigPay configPay = configPayService.selectConfigPayByShopId(shopId);
        ConfigProgram configProgram = configProgramService.selectConfigProgramByShopId(shopId);
        ajax.put(AjaxResult.DATA_TAG, orderGoodsService.insertOrderGoods(orderGoods));
        ajax.put("configPay", configPay);
        ajax.put("configProgram", configProgram);
        return ajax;
    }

    /**
     * 商品订单管理 - 开始服务
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/startOrderGoods")
    public AjaxResult startOrderGoods(@RequestBody OrderGoods orderGoods)
    {
        OrderGoods order = orderGoodsService.selectOrderGoodsByOrderNo(orderGoods.getOrderNo());
        if(StringUtils.isNull(order)){
            return AjaxResult.error("操作失败：订单不存在");
        }
        if(!order.getStatus().equals(UserConstants.STATUS_WAIT)){
            return AjaxResult.error("操作失败：订单状态不可开始");
        }
        Long userId = SecurityUtils.getUserId();
        if(order.getEmployeeUserId().longValue() != userId.longValue()){
            return AjaxResult.error("操作失败：无权限操作");
        }
        order.setIsAccept(UserConstants.YES);
        order.setStatus(UserConstants.STATUS_IN);
        order.setStartTime(new Date());
        orderGoodsService.updateOrderGoods(order);
        return AjaxResult.success(order);
    }

    /**
     * 商品订单管理 - 抢单
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/grabOrderGoods")
    public AjaxResult grabOrderGoods(@RequestBody OrderGoods orderGoods, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if (shopId == null || shopId.equals("")) {
            return error("店铺基本配置失败，参数错误");
        }
        OrderGoods order = orderGoodsService.selectOrderGoodsByOrderNo(orderGoods.getOrderNo());
        if(StringUtils.isNull(order)){
            return AjaxResult.error("操作失败：订单不存在");
        }
        if(order.getIsAccept().equals(UserConstants.YES)){
            return AjaxResult.error("操作失败：订单已被接单");
        }
        if(!order.getStatus().equals(UserConstants.STATUS_WAIT)){
            return AjaxResult.error("操作失败：订单状态不可接单");
        }
        if(!StringUtils.isNull(order.getEmployeeUserId())){
            return AjaxResult.error("操作失败：订单已有服务");
        }
        Long userId = SecurityUtils.getUserId();
        ConfigOrder sysConfigOrder = configOrderService.selectConfigOrderByShopId(shopId);
        if(sysConfigOrder != null){
            // 接单类型（0-指定店员 1-盲盒下单 2-体验下单 3-转让单）
            if(order.getAcceptType().equals(UserConstants.ONE)){
                EmployeeUser employeeUser = employeeUserService.selectUserById(userId);
                if(sysConfigOrder.getStatusBeyond().equals(UserConstants.NO) && employeeUser.getUserLevel() != order.getGoodsLevelId()){
                    // 系统设置 禁止 跨级别抢单
                    return AjaxResult.error("操作失败：店员级别与订单要求级别不一致");
                }
                if(sysConfigOrder.getStatusBeyond().equals(UserConstants.YES)){
                    // 系统设置 允许 跨级别抢单 高等级可以抢低等级
                    Level employeeLevel = levelService.selectLevelById(employeeUser.getUserLevel());
                    Level orderLevel = levelService.selectLevelById(order.getGoodsLevelId());
                    if(employeeLevel.getLevelSort() < orderLevel.getLevelSort()){
                        return AjaxResult.error("操作失败：当前等级不能抢该等级的单");
                    }
                }
            }
            Integer count = orderGoodsService.countOrderGoodsByEmployeeId(userId);
            if(sysConfigOrder.getMaxOrderNum() < count){
                return AjaxResult.error("操作失败：已达最大接单量");
            }
        }
        if(order.getIsExclude().equals(UserConstants.YES)){
            OrderGoods og = new OrderGoods();
            og.setEmployeeUserId(userId);
            og.setOrderUserId(order.getOrderUserId());
            int orderGoodsCountTotal = orderGoodsService.selectOrderGoodsCountTotal(og);
            if (orderGoodsCountTotal > 0){
                return AjaxResult.error("操作失败：该订单已开启排除已接店员");
            }
        }
        order.setIsAccept(UserConstants.YES);
        order.setEmployeeUserId(userId);
        orderGoodsService.updateOrderGoods(order);
        return AjaxResult.success(order);
    }

    /**
     * 商品订单管理 - 完成服务
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/finishOrderGoods")
    public AjaxResult finishOrderGoods(@RequestBody OrderGoods orderGoods)
    {
        return orderGoodsService.finishOrderGoods(orderGoods.getOrderNo());
    }

    /**
     * 商品订单管理 - 店员取消服务
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/employeeCancelOrderGoods")
    public AjaxResult employeeCancelOrderGoods(@RequestBody OrderGoods orderGoods, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        OrderGoods order = orderGoodsService.selectOrderGoodsByOrderNo(orderGoods.getOrderNo());
        if(StringUtils.isNull(order)){
            return AjaxResult.error("操作失败：订单不存在");
        }
        if(!order.getStatus().equals(UserConstants.STATUS_WAIT)){
            return AjaxResult.error("操作失败：订单状态不可取消");
        }
        Long userId = SecurityUtils.getUserId();
        if(!order.getEmployeeUserId().equals(userId)){
            return AjaxResult.error("操作失败：登录人员与订单人员不一致");
        }
        ConfigEmployee configEmployee = configEmployeeService.selectConfigEmployeeByShopId(shopId);
        if(configEmployee != null && configEmployee.getStatusCancelOrder().equals(UserConstants.NO)){
            return AjaxResult.error("操作失败：没有权限取消订单");
        }
        order.setCancelType("employee");
        orderGoodsService.cancelOrderGoods(order);
        return AjaxResult.success();
    }

    /**
     * 商品订单管理 - 客户取消服务
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/customerCancelOrderGoods")
    public AjaxResult customerCancelOrderGoods(@RequestBody OrderGoods orderGoods)
    {
        OrderGoods order = orderGoodsService.selectOrderGoodsByOrderNo(orderGoods.getOrderNo());
        if(StringUtils.isNull(order)){
            return AjaxResult.error("操作失败：订单不存在");
        }
        if(!order.getStatus().equals(UserConstants.STATUS_WAIT)){
            return AjaxResult.error("操作失败：订单状态不可取消");
        }
        Long userId = SecurityUtils.getUserId();
        if(!order.getOrderUserId().equals(userId)){
            return AjaxResult.error("操作失败：无权限操作");
        }
        order.setCancelType("customer");
        orderGoodsService.cancelOrderGoods(order);
        return AjaxResult.success();
    }


    /**
     * 商品订单管理 - 管理员取消服务
     */
    @PreAuthorize("@ss.hasPermi('order:goods:edit')")
    @PostMapping("/adminCancelOrderGoods")
    public AjaxResult adminCancelOrderGoods(@RequestBody OrderGoods orderGoods)
    {
        OrderGoods order = orderGoodsService.selectOrderGoodsByOrderNo(orderGoods.getOrderNo());
        if(StringUtils.isNull(order)){
            return AjaxResult.error("操作失败：订单不存在");
        }
        if(!order.getStatus().equals(UserConstants.STATUS_WAIT)){
            return AjaxResult.error("操作失败：订单状态不可取消");
        }
        order.setCancelType("system");
        orderGoodsService.cancelOrderGoods(order);
        return AjaxResult.success();
    }

    /**
     * 新增商品订单
     */
    @PreAuthorize("@ss.hasPermi('order:goods:add')")
    @Log(title = "商品订单管理 - 新增商品订单", businessType = BusinessType.INSERT)
    @PostMapping()
    public AjaxResult add(@Validated @RequestBody OrderGoods orderGoods, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            orderGoods.setShopId(shopId);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put(AjaxResult.DATA_TAG, orderGoodsService.insertOrderGoods(orderGoods));
        return ajax;
    }

    /**
     * 修改商品订单
     */
    @PreAuthorize("@ss.hasPermi('order:goods:edit')")
    @Log(title = "商品订单管理 - 修改商品订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody OrderGoods orderGoods)
    {
        return toAjax(orderGoodsService.updateOrderGoods(orderGoods));
    }

    /**
     * 删除商品订单
     */
    @PreAuthorize("@ss.hasPermi('order:goods:remove')")
    @Log(title = "商品订单管理 - 删除商品订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderNos}")
    public AjaxResult remove(@PathVariable String[] orderNos)
    {
        return toAjax(orderGoodsService.deleteOrderGoodsByOrderNos(orderNos));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('order:goods:edit')")
    @Log(title = "商品订单管理 - 状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/orderGoodsChangeStatus")
    public AjaxResult changeStatus(@RequestBody OrderGoods orderGoods)
    {
        return toAjax(orderGoodsService.updateOrderGoodsStatus(orderGoods));
    }
}
